package com.bbf.tio.test;

import com.bbf.tio.common.TioConstants;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

  private final ByteBuf byteBuf;

  public NettyClientHandler() {
    String content_10 = "DIRM010042100000000015013649048350512345678901EB";//设备发送命令10
    byte[] bytes = content_10.getBytes();
    byteBuf = Unpooled.buffer(bytes.length);
    byteBuf.writeBytes(bytes);//写入buffer
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    //向服务端发送数据
    ctx.writeAndFlush(byteBuf);
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    //读取服务端发过来的数据
    // Netty
//    ByteBuf buf = (ByteBuf) msg;
//    byte[] bytes = new byte[buf.readableBytes()];
//    buf.readBytes(bytes);
//    String message = new String(bytes, "UTF-8");
//    System.out.println("客户端收到的消息： " + message);

    // t-io
    ByteBuf buf = (ByteBuf) msg;
    //读取最前面4个字节的数据包头
    int bodyLen = buf.readInt();
    // 数据包体，bodyLen - 4，此时因读取指针已经偏移4字节，
    // 用buf.readableBytes()得到的值等于bodyLen - 4
    if (bodyLen > TioConstants.HEADER_LENGHT) {
      bodyLen -= TioConstants.HEADER_LENGHT;
      byte[] bytes = new byte[bodyLen];
      buf.readBytes(bytes);
      String message = new String(bytes, TioConstants.CHARSET_UTF8);
      System.out.println("Netty客户端收到的消息： " + message);
      System.out.println("总长度：" + bodyLen);
    } else {
      System.out.println("报文长度有问题，len = " + bodyLen);
    }
  }

}
